package cristiano.rodrigo.luiz.projetoandroidwn;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class GamesDB {

	private SQLiteDatabase db;
	private SQLiteHelper dbHelper;
	private static final String SCRIPT_DB_DELETE = 
			"DROP TABLE IF EXISTS games";
	
	private static final String SCRIPT_DB_CREATE = 
			"create table games (_id integer primary "
			+ "key autoincrement, titulo text not null, "
			+ "categoria text not null, desenvolvedora text not null);";
	
	public GamesDB(Context ctx) {
		dbHelper = new SQLiteHelper(ctx, "WN", 1, SCRIPT_DB_CREATE,
				SCRIPT_DB_DELETE);
	}
	
	public long inserir(Game g) {
		ContentValues cv = new ContentValues();
		cv.put("titulo", g.titulo);
		cv.put("categoria", g.categoria);
		cv.put("desenvolvedora", g.desenvolvedora);
		db = dbHelper.getWritableDatabase();
		long id = db.insert("games", null, cv);
		g.id = id;
		
		db.close();
		return id;
	}
	
	public long atualizar(Game g) {
		ContentValues cv = new ContentValues();
		cv.put("titulo", g.titulo);
		cv.put("categoria", g.categoria);
		cv.put("desenvolvedora", g.desenvolvedora);

		db = dbHelper.getWritableDatabase();
		long rows = db.update("games", cv, "_id = ?",
				new String[] { String.valueOf(g.id) });
		db.close();
		return rows; // qtde. de linhas afetadas
	}
	
	public int excluir(int id) {
		db = dbHelper.getWritableDatabase();
		int rows = db.delete("games", "_id = ?",
				new String[] { String.valueOf(id) });
		return rows; // qtde. de linhas afetadas
	}
	
	public List<Game> getGames() {
		List<Game> lista = new ArrayList<Game>();

		db = dbHelper.getWritableDatabase();
		Cursor c = db.rawQuery("select * from carros", null);

		while (c.moveToNext()) {
			Game game = fillGame(c);
			lista.add(game);
		}
		c.close();
		db.close();
		return lista;
	}
	
	private Game fillGame(Cursor c) {
		Game game = new Game(
				c.getLong(0), 
				c.getString(1), 
				c.getString(2),
				c.getString(3));
		return game;
	}
}
